package com.pearadmin.controller;

import com.pearadmin.common.annotation.Log;
import com.pearadmin.common.enums.BusinessType;
import com.pearadmin.common.nucleus.base.BaseController;
import com.pearadmin.common.nucleus.domain.response.Result;
import com.pearadmin.system.domain.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping
public class LoginController extends BaseController {

    @GetMapping("login")
    public ModelAndView login(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @Log(title = "登陆",businessType = BusinessType.LOGIN)
    @PostMapping("login")
    public Result login(HttpSession session, SysUser user){
        String msg = "登陆成功";
        String username = user.getUsername().trim();
        String password = user.getPassword().trim();

        //账号密码规则的校监一切交给前端
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //判断用户是否已经登陆
        if(!currentUser.isAuthenticated()) {
            try {
                currentUser.login(token);
            }catch (UnknownAccountException e){
                msg = "账户不存在";
                return failure(msg);
            }catch (IncorrectCredentialsException e){
                msg = "密码错误";
                return failure(msg);
            }catch (LockedAccountException e){
                msg = "账户已被锁定";
                return failure(msg);
            }
        }
        return success(msg);
    }

    @PostMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            subject.logout();
        }
        return success("注销成功");
    }

}
